package org.myhomework.filter;

import org.myhomework.constant.Constants;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Objects;

public class AuthFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        request.setCharacterEncoding("UTF-8");
        String requestURI = ((HttpServletRequest) request).getRequestURI();
        if (Objects.equals("/", requestURI) ||
                requestURI.startsWith("/static") ||
                requestURI.startsWith("/login") ||
                requestURI.contains("ok.jsp") ||
                requestURI.startsWith("/register")) {
            chain.doFilter(request, response);
            return;
        }
        Object o = ((HttpServletRequest) request).getSession().getAttribute(Constants.USER_ID_ATTRIBUTE);
        if (o == null) {
            request.setAttribute("msg", "请先登录");
            request.setAttribute("back", "/");
            request.getRequestDispatcher("/ok.jsp").forward(request, response);
            return;
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
